﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ExcelUtilities.Data
{
    /// <summary>
    /// DataSet扩展函数
    /// </summary>
    public static class DataSetExtensions
    {
        /// <summary>
        /// DataSet转WorkbookData
        /// </summary>
        /// <param name="dataset">要转换的DataSet</param>
        /// <returns></returns>
        public static WorkbookData ToWorkbookData(this DataSet dataset)
        {
            WorkbookData workbookData = new WorkbookData();
            foreach (DataTable table in dataset.Tables)
            {
                var tableData = new TableData();
                tableData.Name = table.TableName;
                foreach (DataRow row in table.Rows)
                {
                    var rowData = new Dictionary<string, CellValue>();
                    foreach (DataColumn column in table.Columns)
                    {
                        rowData.Add(column.ColumnName, new CellValue(row[column.ColumnName]));
                    }
                    tableData.RowDatas.Add(rowData);
                }
                workbookData.SheetDatas.Add(new WorksheetData());
                workbookData.SheetDatas[0].TableDatas.Add(tableData);
            }

            return workbookData;
        }

        /// <summary>
        /// DataTable转WorkbookData
        /// </summary>
        /// <param name="dataset">要转换的DataTable</param>
        /// <returns></returns>
        public static WorkbookData ToWorkbookData(this DataTable datatable)
        {
            WorkbookData workbookData = new WorkbookData();
            var tableData = new TableData();
            tableData.Name = datatable.TableName;
            foreach (DataRow row in datatable.Rows)
            {
                var rowData = new Dictionary<string, CellValue>();
                foreach (DataColumn column in datatable.Columns)
                {
                    rowData.Add(column.ColumnName, new CellValue(row[column.ColumnName]));
                }
                tableData.RowDatas.Add(rowData);
            }
            workbookData.SheetDatas.Add(new WorksheetData());
            workbookData.SheetDatas[0].TableDatas.Add(tableData);


            return workbookData;
        }
    }
}